package com.tidy.seed.admin.system.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.tidy.seed.admin.system.dto.AddRoleIdsByUserIdDTO;
import com.tidy.seed.admin.system.entity.Role;
import com.tidy.seed.admin.system.entity.UserRole;
import com.tidy.seed.admin.system.mapper.RoleMapper;
import com.tidy.seed.admin.system.mapper.UserRoleMapper;
import com.tidy.seed.admin.system.service.UserRoleService;
import com.tidy.seed.admin.system.vo.UserRoleVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author HZ-ZY
 * @since 2025-08-06
 */
@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRole> implements UserRoleService {
    @Resource
    private UserRoleMapper userRoleMapper;
    @Resource
    private RoleMapper roleMapper;

    @Override
    public Integer[] findRoleIdsByUserId(Integer userId) {
        List<UserRole> UserRoleList = userRoleMapper.selectList(Wrappers.<UserRole>query().eq("user_id", userId));
        return UserRoleList.stream()
                .map(UserRole::getRoleId)  // 假设RoleApi类有getApiId()方法获取接口ID
                .toArray(Integer[]::new);
    }

    @Override
    public Boolean addRoleIdsByUserId(AddRoleIdsByUserIdDTO dto) {
        //删除所有再新增
        userRoleMapper.delete(Wrappers.<UserRole>query().eq("user_id", dto.getUserId()));
        List<UserRole> UserRoleList = Arrays.stream(dto.getRoleIds())
                .map(roleId -> {
                    UserRole userRole = new UserRole();
                    userRole.setUserId(dto.getUserId());
                    userRole.setRoleId(roleId);
                    return userRole;
                })
                .collect(Collectors.toList());
        return this.saveBatch(UserRoleList);
    }

    @Override
    public List<Role> findRolesByUserId(Integer userId) {
        List<UserRole> UserRoleList = userRoleMapper.selectList(Wrappers.<UserRole>query().eq("user_id", userId));
        List<Integer> collect = UserRoleList.stream().map(UserRole::getRoleId).collect(Collectors.toList());
        if (collect.isEmpty()) return Collections.emptyList();
        return roleMapper.selectBatchIds(collect);
    }

    @Override
    public List<UserRoleVO> findRolesByUserIds(List<Integer> userIds) {
        return userRoleMapper.findRolesByUserIds(userIds);
    }


}
